package com.dd.security.component;

import com.alibaba.fastjson.JSONObject;
import com.dd.common.entity.view.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户未登录或登录超时的处理方式
 */
@Slf4j
public class MallAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        CommonResult result = CommonResult.unauthorized(authException.getMessage());

        log.warn("用户未登录{},不能访问{}",authException,request.getRequestURI());
        response.setStatus(401);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().write(JSONObject.toJSONString(result));
        response.getWriter().flush();
    }
}
